package cn.webrx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@WebServlet("/uploads")
@MultipartConfig
public class Uploads extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理post中文乱码
        req.setCharacterEncoding("utf-8");
        String author = req.getParameter("author");
        System.out.println(author);


        //在服务器上建立一个目录
        String path = req.getServletContext().getRealPath("/upload/");
        File f = new File(path);
        if (!f.exists()) f.mkdirs();

        //处理上传表单的文件
        Collection<Part> parts = req.getParts(); //getParts() 包括了所有表单内容
        //image/jpg  image/png image/jpeg auth
        AtomicInteger num = new AtomicInteger();
        parts.stream().filter(p -> p.getContentType() != null).forEach(file -> {
            System.out.println(file.getSubmittedFileName());
            String filename = file.getSubmittedFileName();
            String newfilename = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
            try {
                file.write(path + newfilename);
                num.getAndIncrement();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        req.setAttribute("num", num.get());

        //重定向
        //resp.sendRedirect();

        //转发到result.jsp中显示上传结果
        req.getRequestDispatcher("result.jsp").forward(req, resp);

    }
}
